local allowed_tokens = {
    ["Bearer myapikey1"] = true,
    ["Bearer myapikey2"] = true
}
local auth_header = ngx.req.get_headers()["Authorization"]
if not auth_header or not allowed_tokens[auth_header] then
    return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
ngx.req.read_body()
local body = ngx.req.get_body_data()
local json = require("cjson")
local data = json.decode(body)
local dict = {
    ["deepseek-r1"] = {
        {url = "https://ark.cn-beijing.volces.com/api/v3", key = "xxx", model = "deepseek-r1-250120"},
        {url = "https://api.siliconflow.cn/v1", key = "sk-xxx", model = "deepseek-ai/DeepSeek-R1"}
    },
    ["deepseek-v3"] = {
        {url = "https://ark.cn-beijing.volces.com/api/v3", key = "xxx", model = "deepseek-v3-241226"},
        {url = "https://api.siliconflow.cn/v1", key = "sk-xxx", model = "deepseek-ai/DeepSeek-V3"}
    },
    ["Doubao-1.5-pro-32k"] = {
        {url = "https://ark.cn-beijing.volces.com/api/v3", key = "xxx", model = "ep-20250226144041-f58mg"},
    },
    ["qwen-plus"] = {
        {url = "https://dashscope.aliyuncs.com/compatible-mode/v1", key = "sk-xxx"},
    },
    ["qwen-max"] = {
        {url = "https://dashscope.aliyuncs.com/compatible-mode/v1", key = "sk-xxx"},
    },
    ["gpt-4o"] = {
        {url = "https://api.openai.com/v1", key = "sk-xxx"},
    },
    ["gpt-4o-mini"] = {
        {url = "http://api.openai.com/v1", key = "sk-xxx"},
    }
}
local conf = nil
if dict[data.model] then
    local arr = dict[data.model]
    if #arr == 1 then
        conf = arr[1]
    else
        conf = arr[math.random(1, #arr)]
    end
end
if conf == nil then
    return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
ngx.var.base_url = conf.url
local authorization_header = "Bearer " .. conf.key
ngx.req.set_header("Authorization", authorization_header)
if conf.model ~= nil then
    data.model = conf.model
    local new_body = json.encode(data)
    ngx.req.set_body_data(new_body)
end